package com.xxl.job.executor.sample.frameless.test.wait_notifyDemo;

public class Difficult5 {

    static final Object room = new Object();
    static boolean hasCigarette = false;
    static boolean hasTakeout = false;

    //将 if 改为 while
    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            synchronized (room) {
                System.out.println(Thread.currentThread().getName() + "：有烟没？" + hasCigarette);
                while (!hasCigarette) {
                    System.out.println(Thread.currentThread().getName() + ":没烟，先歇会！");
                    try {
                        room.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "：有烟没？" + hasCigarette);
                if (hasCigarette) {
                    System.out.println("可以开始干活了！");
                }else {
                    System.out.println("没干成活。。。");
                }
            }
        },"小王").start();
        new Thread(() -> {
            synchronized (room) {
                System.out.println(Thread.currentThread().getName() + ":外卖送到没？" + hasTakeout);
                if (!hasTakeout) {
                    System.out.println(Thread.currentThread().getName() + ":没外卖，先歇会儿？");
                }
                try {
                    room.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "：外卖送到没？" + hasTakeout);
            if (hasTakeout) {
                System.out.println(Thread.currentThread().getName() + ":可以开始干活了！");
            }else {
                System.out.println(Thread.currentThread().getName() + ":没干成活。。。");
            }
        },"老王").start();

        Thread.sleep(1000);

        new Thread(() -> {
            synchronized (room) {
                hasTakeout = true;
                System.out.println(Thread.currentThread().getName() + "：外卖到了！");
                room.notifyAll();
            }
        },"送外卖的").start();
    }
}
